<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="考核表名称：">
                            <el-input v-model="transferVal" placeholder="请输入考核表名称" />
                        </el-form-item> -->
						<el-form-item>
							<el-button v-if="$hasPer('SafetyAssessment1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
							<el-button v-if="$hasPer('SafetyAssessment7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
							<el-button v-if="$hasPer('SafetyAssessment2:download')" icon="ele-Download" @click="down"> 下载模板 </el-button>
							<el-upload
								v-if="$hasPer('SafetyAssessment3:export')"
								action="#"
								multiple
								:auto-upload="false"
								:show-file-list="false"
								accept=".xlsx"
								:on-change="(file: any) => { uploadFile1(file) }"
								style="margin-left: 10px; padding-top: 4px"
							>
								<template #trigger>
									<el-button icon="ele-Upload">导入Excel</el-button>
								</template>
							</el-upload>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table ref="excelRef" :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="考核表名称" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="name" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.name }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="60" :show-overflow-tooltip="true" label="优秀线" prop="excellentScore" align="center"/>
										<el-table-column min-width="60" :show-overflow-tooltip="true" label="及格线" prop="passScore" align="center"/>
										<el-table-column min-width="100" :show-overflow-tooltip="true" prop="createdTime" label="创建时间" align="center" />
										<el-table-column min-width="80" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="100" :show-overflow-tooltip="true" label="更新时间" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="80" :show-overflow-tooltip="true" label="更新人" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedUserName">{{ scope.row.updatedUserName }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="300" :show-overflow-tooltip="true" label="备注" align="center">
											<template #default="scope">
												<span v-if="scope.row.remark">{{ scope.row.remark }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="140" label="操作" align="center" fixed="right">
											<el-table-column min-width="140" align="center" fixed="right">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button v-if="$hasPer('SafetyAssessment4:create')" @click="subitemAssessment(scope.row)" class="icon-e" icon="ele-Plus" size="small" text type="primary">
															子项考核
														</el-button>
														<el-button v-if="$hasPer('SafetyAssessment5:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>
														<el-button v-if="$hasPer('SafetyAssessment6:delete')" @click="deleteHandle(scope.row)" class="icon-e" icon="ele-Delete" size="small" text type="danger">
															删除
														</el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="saveId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form label-width="100px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="name" label="考核表名称">
							<el-input type="textarea" v-model="ruleForm.name" placeholder="考核表名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="excellentScore" label="优秀线">
							<!-- <el-input  v-model="ruleForm.excellentScore" placeholder="优秀线" clearable /> -->
							<el-input-number style="width: 100%;" v-model="ruleForm.excellentScore" :min="0" :max="1000" placeholder="优秀线" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="passScore" label="及格线">
							<!-- <el-input  v-model="ruleForm.passScore" placeholder="及格线" clearable /> -->
							<el-input-number style="width: 100%;" v-model="ruleForm.passScore" :min="0" :max="1000" placeholder="及格线" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="备注">
							<el-input type="textarea" v-model="ruleForm.remark" placeholder="备注" clearable />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 新增子项考核 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="subitemDialogVisible" title="新增子项考核" width="50%" @close="cancelSubitemClick">
			<el-form label-width="120px" ref="subitemRuleFormRef" :model="subitemRuleForm" size="small" :rules="subitemRules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item prop="projectName" label="项目子项考核名称">
							<el-input v-model="subitemRuleForm.projectName" placeholder="项目名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item prop="content" label="考核内容">
							<el-input type="textarea" v-model="subitemRuleForm.content" placeholder="考核内容" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item prop="gradingCriteria" label="评分标准">
							<el-input type="textarea" v-model="subitemRuleForm.gradingCriteria" placeholder="评分标准" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item prop="criterionScores" label="标准分">
							<el-input v-model="subitemRuleForm.criterionScores" placeholder="标准分" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item>
							<el-button v-if="!addAndEdit" @click="generateSubitem(subitemRuleFormRef)" class="icon-e" icon="ele-Plus" size="small" type="primary">新增</el-button>
							<el-button v-else @click="generateSubitem(subitemRuleFormRef)" class="icon-e" icon="ele-Edit" size="small" type="primary">更新</el-button>
							<el-button @click="resetSubitem" class="icon-e" icon="ele-Refresh" size="small">重置</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-divider content-position="left"> 新增子项考核内容查看 </el-divider>
			<el-table :data="subitemTableData" size="small" border style="width: 100%">
				<el-table-column type="index" align="center" label="序号" width="60" />
				<el-table-column prop="projectName" label="项目子项考核名称" min-width="100" align="center" />
				<el-table-column prop="content" label="考核内容" min-width="140" align="center" />
				<el-table-column prop="gradingCriteria" label="评分标准" min-width="100" align="center" />
				<el-table-column prop="criterionScores" label="标准分" min-width="60" align="center" />
				<el-table-column label="操作" min-width="100" align="center">
					<template #default="scope">
						<el-button @click="handleEdit(scope.row)" text type="primary" size="small">编辑</el-button>
						<el-button @click="deleteSubitem(scope.row)" text type="danger" size="small">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelSubitemClick">取消</el-button>
                    <el-button type="primary" @click="controlSubitemClick(subitemRuleFormRef)">确定</el-button>
                </span>
            </template> -->
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted,toRaw } from 'vue';
import getTableData from '/@/utils/getTableData';
import {
	getSafetyProductionStandardApi,
	deleteSubSafetyProductionStandardApi,
	editSafetyProductionStandardApi,
	addSafetyProductionStandardApi,
	SecurityGenerationAssessmentStandardDownload,
	addSubSafetyProductionStandardApi,
	getSubSafetyProductionStandardApi,
	editSubSafetyProductionStandardApi,
	deleteSafetyProductionStandardApi,
	SecurityGenerationAssessmentStandardUpload,
	getRiskAssessmentTableApi,
} from '/@/api/sms/HazardousChemicalsInterface';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import SearchModel from '/@/views/sms/component/search-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
/***** 查询 *****/
let searchObj: any = reactive({});
const transferVal = ref();
const searchClick = () => {
	// searchObj.Name = transferVal.value
	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};
const resetClick = () => {
	// transferVal.value = ''
	searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
			// console.log(i);
		});
	}
	initInfoFun();
};
/***** 新增 *****/
const showDialogVisible = ref(false);
const ruleForm = reactive({
	name: '',
	passScore: 0,
	excellentScore: 0,
	remark: '',
});
const addNodeClick = async () => {
	showDialogVisible.value = true;
};

/***** 编辑 *****/
const saveId = ref();
const nodeClick = async (row: any) => {
	if (row.n_Id) {
		saveId.value = row.n_Id;
		ruleForm.name = row.name;
		ruleForm.passScore = row.passScore;
		ruleForm.excellentScore = row.excellentScore;
		ruleForm.remark = row.remark;
	}
	showDialogVisible.value = true;
};

/*** 删除 */
const deleteHandle = async (item:any) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { id: item.n_Id };
			try {
				const bl = employeeEvaluaFormList.value.some((i) => i.n_Id == item.n_Id);
				console.log(bl,"bl");
				if (bl) return ElMessage.error('该考核表已绑定员工考核，不能删除');
				let res: any = await deleteSafetyProductionStandardApi(param);
				if (res.success) {
					getData();
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};

/***** 新增表单校验和事件 *****/
const ruleFormRef = ref();
const rules = reactive({
	name: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	excellentScore: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	passScore: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});
const cancelUseClick = () => {
	ruleForm.name = '';
	ruleForm.excellentScore =0;
	ruleForm.passScore =0;
	ruleForm.remark = '';
	saveId.value = 0;
	ruleFormRef.value.clearValidate();
	showDialogVisible.value = false;
};
const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (saveId.value) {
				editSafetyProductionStandardApi({ ...ruleForm, id: saveId.value }).then(() => {
					cancelUseClick();
					getData();
				});
			} else {
				addSafetyProductionStandardApi(ruleForm).then(() => {
					cancelUseClick();
					getData();
				});
			}
		} else {
			console.log('error submit!', fields);
		}
	});
};

const pathData = ref(import.meta.env.VITE_API_URL + '/') // 获取地址
const down = async () => {
	// const res = await SecurityGenerationAssessmentStandardDownload();
	window.open(toRaw(pathData.value) + 'Upload/SMS/Batch/SafetyAssessment.xlsx','_blank') // 打开新页面
	console.log(toRaw(pathData.value) + 'Upload/SMS/Batch/SafetyAssessment.xlsx','_blank');
};

const uploadFile1 = async (item: any) => {
	let arr: any = [];
	arr.push(item.raw);
	console.log(item);
	setTimeout(() => {
		SecurityGenerationAssessmentStandardUpload({ file: arr });
		ElMessage.success('上传成功');
	}, 100);
};

/***** 子项考核表单校验和事件 *****/
const subitemDialogVisible = ref(false);
const subitemRuleFormRef = ref();
const subitemRuleForm = reactive({
	formId: 0,
	projectName: '',
	content: '',
	criterionScores: 0,
	gradingCriteria: '',
});
const subitemAssessment = async (row: any) => {
	saveId.value = row.n_Id;
	const res = await getSubSafetyProductionStandardApi({ pageSize: 999, pageNo: 1, FormId: row.n_Id });
	subitemTableData.value = res.data.rows;
	subitemDialogVisible.value = true;
};
const cancelSubitemClick = () => {
	subitemDialogVisible.value = false;
	saveId.value = 0;
	subitemTableData.value = [];
	subitemRuleForm.formId = 0;
	subitemRuleForm.projectName = '';
	subitemRuleForm.content = '';
	subitemRuleForm.criterionScores = 0;
	subitemRuleForm.gradingCriteria = '';
	addAndEdit.value = false;
	subitemRuleFormRef.value!.clearValidate();
};
const subitemRules = reactive({
	projectName: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	criterionScores: [
		{ required: true, message: '内容不能为空', trigger: 'blur' },
		{ pattern: /^[1-9]\d*$/, message: '请输入数字', trigger: 'blur' },
	],
	gradingCriteria: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});

/***** 子项考核新增编辑 *****/
const subitemTableData = ref([]);
const addAndEdit = ref(false);
const generateSubitem = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (subitemRuleForm.id) {
				editSubSafetyProductionStandardApi(subitemRuleForm).then(() => {
					getSubSafetyProductionStandardApi({ pageSize: 999, pageNo: 1, FormId: saveId.value }).then((res) => {
						subitemTableData.value = res.data.rows;
						resetSubitem();
					});
				});
			} else {
				addSubSafetyProductionStandardApi({ ...subitemRuleForm, formId: saveId.value }).then(() => {
					getSubSafetyProductionStandardApi({ pageSize: 999, pageNo: 1, FormId: saveId.value }).then((res) => {
						subitemTableData.value = res.data.rows;
						addAndEdit.value = false;
						subitemRuleForm.projectName = '';
						subitemRuleForm.content = '';
						subitemRuleForm.criterionScores = 0;
						subitemRuleForm.gradingCriteria = '';
					});
				});
			}
		} else {
			console.log('error submit!', fields);
		}
	});
};
// 子项考核重置
const resetSubitem = () => {
	subitemRuleForm.projectName = '';
	subitemRuleForm.content = '';
	subitemRuleForm.criterionScores = 0;
	subitemRuleForm.gradingCriteria = '';
	addAndEdit.value = false;
	subitemRuleForm.id = '';
};
//子项考核编辑
const handleEdit = (row: any) => {
	subitemRuleForm.projectName = row.projectName;
	subitemRuleForm.content = row.content;
	subitemRuleForm.criterionScores = row.criterionScores;
	subitemRuleForm.gradingCriteria = row.gradingCriteria;
	subitemRuleForm.id = row.n_Id;
	subitemRuleForm.formId = row.formId;
	addAndEdit.value = true;
};

/***** 子项考核删除 *****/
const deleteSubitem = (item: Number) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { id: item.n_Id };
			try {
				let res: any = await deleteSubSafetyProductionStandardApi(param);
				if (res.success) {
					const res = await getSubSafetyProductionStandardApi({ pageSize: 999, pageNo: 1, FormId: saveId.value });
					subitemTableData.value = res.data.rows;
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};

/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'name', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'Name', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '考核表名字', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};

const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};

const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
	console.log(row);
	if (columnIndex === 1) {
		if (rowIndex % 2 === 0) {
			return {
				rowspan: 2,
				colspan: 1,
			};
		} else {
			return {
				rowspan: 0,
				colspan: 0,
			};
		}
	}
};

/*** ================================= 导出数据函数操作 ================================= */
const excelRef: any = ref(null);
const handleExport = () => {
	if (excelRef.value) {
		if (excelRef.value.data.length !== 0) {
			let tableExcel: any = [];
			let tableArr = excelRef.value.data;
			tableArr.map((item: any) => {
				let tableObj: any = {};
				tableObj['考核表名称'] = item.name ? item.name : '-';
				tableObj['优秀线'] = item.excellentScore ? item.excellentScore : '-';
				tableObj['及格线'] = item.passScore ? item.passScore : '-';
				tableObj['备注'] = item.remark ? item.remark : '-';

				tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
				tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
				tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
				tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
				tableExcel.push(tableObj);
			});
			exportToExcel(tableExcel, '安全生产考核标准.xlsx');
		} else {
			ElMessage({
				type: 'error',
				message: '暂无数据导出',
			});
		}
	}
};

const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getSafetyProductionStandardApi, {}, searchObj);
const employeeEvaluaFormList: any = ref([]);
onMounted(async () => {
	initInfoFun();
	const res = await getRiskAssessmentTableApi();
	employeeEvaluaFormList.value = res.data;
});
</script>

<style lang="scss">
@import '../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
